<template>
  <view class="live-container">
    <!-- 视频播放区域 -->
    <view class="video-section">
      <video
        :src="state.pullurl"
        class="live-video"
        :controls="false"
        object-fit="contain"
        :loop="true"
        :is-live="true"
        :autoplay="true"
        :show-center-play-btn="true"
        :enable-progress-gesture="true"
        :show-fullscreen-btn="true"
        @error="onPlayError"
        @play="onVideoPlay"
        @pause="onVideoPause"
      ></video>

      <!-- 自定义控制层 -->
      <view class="video-controls" v-if="!state.isPlaying" @click="togglePlay">
        <view class="play-btn">
          <text class="play-icon">▶</text>
        </view>
      </view>

      <!-- 直播信息栏 -->
      <view class="live-info-bar">
        <view class="streamer-info">
          <image class="avatar" :src="state.streamerAvatar || '/static/logo@3x.png'" mode="aspectFill"></image>
          <text class="nickname">{{ state.streamerName || '主播' }}</text>
        </view>
        <view class="viewers-count">
          <text class="count-text">{{ state.viewersCount || 0 }}人观看</text>
        </view>
      </view>

      <!-- 返回按钮 -->
      <view class="back-btn" @click="goBack">
        <text class="back-icon">←</text>
      </view>
    </view>

    <!-- 评论区域 -->
    <view class="comment-section">
      <!-- 评论列表 -->
      <list class="comment-list" :show-scrollbar="false" :bounce="true">
        <cell v-for="(item, index) in state.comments" :key="index">
          <view class="comment-item">
            <image class="comment-avatar" :src="item.avatar" mode="aspectFill"></image>
            <view class="comment-content">
              <view class="comment-header">
                <text class="comment-username">{{ item.username }}</text>
                <text class="comment-time">{{ item.time }}</text>
              </view>
              <text class="comment-text">{{ item.content }}</text>
            </view>
          </view>
        </cell>
        <cell v-if="state.comments.length === 0">
          <view class="empty-comments">
            <text class="empty-text">暂无评论，快来发表第一条评论吧</text>
          </view>
        </cell>
        <cell v-if="state.isLoading">
          <view class="loading">
            <text class="loading-text">加载中...</text>
          </view>
        </cell>
      </list>

      <!-- 评论输入框 -->
      <view class="comment-input-area">
        <input
          class="comment-input"
          type="text"
          v-model="state.commentText"
          placeholder="说点什么..."
          confirm-type="send"
          @confirm="submitComment"
        />
        <view class="send-btn" @click="submitComment">
          <text class="send-text">发送</text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="state.initialLoading">
      <view class="loading-content">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script>
  import sheep from '@/sheep';

  export default {
    data() {
      return {
        state: {
          pullurl: '',
          isPlaying: false,
          initialLoading: true,
          isLoading: false,
          streamerName: '',
          streamerAvatar: '',
          viewersCount: 0,
          commentText: '',
          comments: []
        },
        videoContext: null
      };
    },
    onLoad(e) {
      // 获取直播流地址
      this.state.pullurl = e.pullurl;
      
      // 模拟获取直播信息
      this.getLiveInfo();
      
      // 模拟获取评论列表
      this.getComments();
      
      // 2秒后关闭加载状态
      setTimeout(() => {
        this.state.initialLoading = false;
      }, 2000);
    },
    onReady() {
      // 获取视频上下文
      this.videoContext = uni.createVideoContext('liveVideo', this);
    },
    methods: {
      // 播放错误处理
      onPlayError(e) {
        console.error('直播播放错误:', e);
        // 打印更详细的错误信息
        if (e && e.detail) {
          console.error('错误详情:', JSON.stringify(e.detail));
        }
        uni.showToast({
          title: '播放出错，请稍后重试',
          icon: 'none',
          duration: 3000,
        });

        // 尝试重新加载视频
        setTimeout(() => {
          console.log('尝试重新加载视频');
          if (this.videoContext) {
            this.videoContext.stop();
            this.videoContext.play();
          }
        }, 3000);
      },
      // 视频开始播放
      onVideoPlay(e) {
        console.log('视频开始播放', e);
        this.state.isPlaying = true;
      },
      // 视频暂停播放
      onVideoPause(e) {
        console.log('视频暂停播放', e);
        this.state.isPlaying = false;
      },
      // 切换播放状态
      togglePlay() {
        if (this.state.isPlaying) {
          this.videoContext.pause();
        } else {
          this.videoContext.play();
        }
        this.state.isPlaying = !this.state.isPlaying;
      },
      // 返回上一页
      goBack() {
        uni.navigateBack();
      },
      // 提交评论
      submitComment() {
        if (!this.state.commentText.trim()) {
          uni.showToast({
            title: '请输入评论内容',
            icon: 'none'
          });
          return;
        }
        
        // 模拟提交评论
        const newComment = {
          id: Date.now(),
          username: '用户' + Math.floor(Math.random() * 1000),
          avatar: '/static/logo@3x.png',
          content: this.state.commentText,
          time: this.formatTime(new Date())
        };
        
        // 添加到评论列表
        this.state.comments.unshift(newComment);
        
        // 清空输入框
        this.state.commentText = '';
        
        // 显示提交成功
        uni.showToast({
          title: '评论成功',
          icon: 'success'
        });
        
        // 实际项目中应该调用API提交评论
        // sheep.$api.yy.submitComment({
        //   live_id: liveId,
        //   content: this.state.commentText
        // }).then(res => {
        //   if (res.code === 1) {
        //     this.getComments(); // 重新获取评论列表
        //     this.state.commentText = '';
        //   }
        // });
      },
      // 获取直播信息
      getLiveInfo() {
        // 模拟获取直播信息
        setTimeout(() => {
          this.state.streamerName = '主播名称';
          this.state.streamerAvatar = '/static/logo@3x.png';
          this.state.viewersCount = Math.floor(Math.random() * 1000);
        }, 1000);
        
        // 实际项目中应该调用API获取直播信息
        // sheep.$api.yy.getLiveInfo({
        //   id: liveId
        // }).then(res => {
        //   if (res.code === 1) {
        //     this.state.streamerName = res.data.name;
        //     this.state.streamerAvatar = res.data.avatar;
        //     this.state.viewersCount = res.data.viewers_count;
        //   }
        // });
      },
      // 获取评论列表
      getComments() {
        this.state.isLoading = true;
        
        // 模拟获取评论列表
        setTimeout(() => {
          const mockComments = [];
          for (let i = 0; i < 10; i++) {
            mockComments.push({
              id: i,
              username: '用户' + Math.floor(Math.random() * 1000),
              avatar: '/static/logo@3x.png',
              content: '这是一条评论内容，随机数：' + Math.floor(Math.random() * 1000),
              time: this.formatTime(new Date(Date.now() - i * 60000))
            });
          }
          this.state.comments = mockComments;
          this.state.isLoading = false;
        }, 1500);
        
        // 实际项目中应该调用API获取评论列表
        // sheep.$api.yy.getComments({
        //   live_id: liveId,
        //   page: 1,
        //   limit: 20
        // }).then(res => {
        //   if (res.code === 1) {
        //     this.state.comments = res.data.list;
        //   }
        //   this.state.isLoading = false;
        // }).catch(() => {
        //   this.state.isLoading = false;
        // });
      },
      // 格式化时间
      formatTime(date) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${hours}:${minutes}`;
      }
    }
  };
</script>

<style>
  .live-container {
    flex: 1;
    background-color: #000;
  }
  
  /* 视频播放区域 */
  .video-section {
    position: relative;
    width: 750rpx;
    height: 450rpx;
  }
  
  .live-video {
    width: 750rpx;
    height: 450rpx;
    background-color: #000;
  }
  
  /* 视频控制层 */
  .video-controls {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.3);
  }
  
  .play-btn {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50rpx;
    background-color: rgba(255, 255, 255, 0.3);
    justify-content: center;
    align-items: center;
  }
  
  .play-icon {
    color: #fff;
    font-size: 50rpx;
  }
  
  /* 直播信息栏 */
  .live-info-bar {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    right: 20rpx;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
  
  .streamer-info {
    flex-direction: row;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 30rpx;
    padding: 10rpx 20rpx;
  }
  
  .avatar {
    width: 60rpx;
    height: 60rpx;
    border-radius: 30rpx;
    margin-right: 10rpx;
  }
  
  .nickname {
    color: #fff;
    font-size: 28rpx;
  }
  
  .viewers-count {
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 30rpx;
    padding: 10rpx 20rpx;
  }
  
  .count-text {
    color: #fff;
    font-size: 24rpx;
  }
  
  /* 返回按钮 */
  .back-btn {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    background-color: rgba(0, 0, 0, 0.5);
    justify-content: center;
    align-items: center;
  }
  
  .back-icon {
    color: #fff;
    font-size: 40rpx;
  }
  
  /* 评论区域 */
  .comment-section {
    flex: 1;
    background-color: #f8f8f8;
  }
  
  .comment-list {
    flex: 1;
    padding: 20rpx;
  }
  
  .comment-item {
    flex-direction: row;
    padding: 20rpx;
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 10rpx;
  }
  
  .comment-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
  }
  
  .comment-content {
    flex: 1;
  }
  
  .comment-header {
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 10rpx;
  }
  
  .comment-username {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
  }
  
  .comment-time {
    font-size: 24rpx;
    color: #999;
  }
  
  .comment-text {
    font-size: 28rpx;
    color: #666;
    line-height: 40rpx;
  }
  
  .empty-comments {
    padding: 100rpx 0;
    justify-content: center;
    align-items: center;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
  
  .loading {
    padding: 20rpx 0;
    justify-content: center;
    align-items: center;
  }
  
  .loading-text {
    font-size: 24rpx;
    color: #999;
  }
  
  /* 评论输入区域 */
  .comment-input-area {
    flex-direction: row;
    padding: 20rpx;
    background-color: #fff;
    border-top-width: 1rpx;
    border-top-color: #eee;
  }
  
  .comment-input {
    flex: 1;
    height: 80rpx;
    background-color: #f5f5f5;
    border-radius: 40rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
    margin-right: 20rpx;
  }
  
  .send-btn {
    width: 120rpx;
    height: 80rpx;
    background-color: #0788C8;
    border-radius: 40rpx;
    justify-content: center;
    align-items: center;
  }
  
  .send-text {
    color: #fff;
    font-size: 28rpx;
  }
  
  /* 加载状态 */
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    justify-content: center;
    align-items: center;
  }
  
  .loading-content {
    width: 200rpx;
    height: 200rpx;
    background-color: rgba(0, 0, 0, 0.7);
    border-radius: 20rpx;
    justify-content: center;
    align-items: center;
  }
</style>